varying vec3 pos,l,n,v,h;
varying vec2 texCoord;
uniform vec3 eyePos;
uniform float time;
uniform vec3 lightPos;
uniform sampler2D road; 
uniform sampler2D grass;
uniform sampler2D caustics;
uniform sampler2D shadowMap1;
uniform sampler2D shadowMap2;
uniform sampler2D shadowMap3;
uniform sampler2D shadowMap4;    
varying vec2 offset;
varying vec4 posit1;
varying vec4 posit2;
varying vec4 posit3;
varying vec4 posit4;
  
float dist(vec3 a, vec3 b) {
	vec3 c = a - b;
	return sqrt(c.x*c.x + c.y*c.y + c.z*c.z);
}  
float module(vec3 a, vec3 b) {
    vec3 c = a - b;
    return sqrt(c.x*c.x + c.y*c.y + c.z*c.z);
} 
void main(void) {
   float fr = module(eyePos,pos);
   float start = 0.0;
   float end = 1000.0;
   float summar = min(max( dot(normalize(l), vec3(0.0,0.0,1.0)), 0.1 ),0.5);
   if(fr > end) { 
   		gl_FragColor = vec4(summar);
   		return;
   } 
   float  r;
   n = normalize(n);
   float fren = abs(n.z);
   if(fren > 0.97) fren = 1.01;
   else if(fren < 0.92) fren = 0.01;
   else fren = 1.01 - (0.97 - fren)*20.0;
   r =  max(0.0,dot(l, n));
   if(pos.z < 0) fren = 0.0;
   vec4 color;
   if(fren == 1.0) color = texture2D(grass,texCoord);
   else if(fren == 0.0) color = texture2D(road,texCoord);
   else color = texture2D(grass,texCoord)*fren + texture2D(road,texCoord)*(1.01-fren);
   float transparency = color.w;
   gl_FragColor = color*r;
   //shadow map

    vec3 shad_coor = (posit1.xyz / posit1.w) * 0.5 + 0.5;
    vec4 s = texture2D(shadowMap1,shad_coor.xy)+0.001;
    float pmax = 1.0;
    if(shad_coor.z >= s.x) {
    	float mu = s.x;
    	pmax = sqrt(mu /shad_coor.z) -0.3;
    }
	gl_FragColor.xyz*=pmax;

	
   gl_FragColor.w = transparency;
   if(pos.z > 0.0 && fr > start) {
    fr = 1.0/(1.0 - (fr/end));
    gl_FragColor.x = summar + (gl_FragColor.x - summar)/fr;
    gl_FragColor.y = summar + (gl_FragColor.y - summar)/fr;
    gl_FragColor.z = summar + (gl_FragColor.z - summar)/fr;
    }
    vec2 offset2;
    offset2.x = offset.y;
    offset2.y = offset.x;
    float fr_caustics = min(1.0, -(pos.z + 2.0));
	if(pos.z < -2.0 && shad_coor.z < s.x) gl_FragColor += (texture2D(caustics,texCoord+offset+vec2(-time+0.41,-time+0.29)) + texture2D(caustics,texCoord+offset2+vec2(time,0.0)))*fr_caustics/4.0;
	

}
